package com.xiaochi.wx.controller;

import com.xiaochi.wx.handler.WxChatMsgFactory;
import com.xiaochi.wx.handler.WxChatMsgHandler;
import com.xiaochi.wx.utils.MessageUtil;
import com.xiaochi.wx.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * @author zqx
 * @since 2024/8/31
 */
@RestController
@Slf4j
public class CallBackController {

    private static final String token = "ajdfklaajfa";

    @Resource
    private WxChatMsgFactory wxChatMsgFactory;

    @RequestMapping("/test")
    public String test(){
        return "test";
    }

    @GetMapping("/callback")
    public String callBack(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr")String echostr){
        log.info("get验签请求参数：signature:{},timestamp:{},nonce:{},schostr:{}",signature,timestamp,nonce,echostr);
        String sha1 = SHA1.getSHA1(token, timestamp, nonce, "");
        if (echostr.equals(sha1)){
            return echostr;
        }else {
            return "调用失败";
        }
    }

    @PostMapping(value = "/callback",produces = "application/xml;charset=UTF-8")
    public String callBack(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam(value = "msg_signature",required = false)String msgSignature){
        log.info("post接收到消息：request:{}",requestBody);
        Map<String, String> stringStringMap = MessageUtil.parseXml(requestBody);
        String event = stringStringMap.get("Event") == null ? "" : stringStringMap.get("Event");
        String msgType = stringStringMap.get("MsgType");
        log.info("msgType:{},event:{}", msgType, event);
        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if (!StringUtils.isEmpty(event)) {
            sb.append(".");
            sb.append(event);
        }
        String msgTypeKey = sb.toString();
        WxChatMsgHandler msgTypeHandler = wxChatMsgFactory.getMsgTypeHandler(msgTypeKey);
        if (Objects.isNull(msgTypeHandler)) {
            return "unknown";
        }
        String replyContent = msgTypeHandler.dealMsg(stringStringMap);
        log.info("replyContent:{}", replyContent);
        return replyContent;
    }
}
